﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MShop.Core.Domain;
using MShop.Core.Service;
using System.Web.Mvc;

namespace MShop.Core.DataAccess
{
    [Castle.Core.Transient(Lifestyle = Castle.Core.LifestyleType.Transient)]
    public class AreaGroupDao : CommonDao<AreaGroup>, IAreaGroupDao
    {
        private readonly IRecursionSort<AreaGroup> _RecursionService;
        private readonly IObjectContextProvider _Provider;
        public AreaGroupDao(IObjectContextProvider provider, IRecursionSort<AreaGroup> recursionservicce)
            : base(provider)
        {
            _Provider = provider;
            _RecursionService = recursionservicce;       
            
        }


        public override void Delete(AreaGroup entity)
        {
            HashSet<AreaGroup> hashset = new HashSet<AreaGroup>();

            RecursiveAreas(entity, ref hashset);

            base.Delete(hashset);

            base.Delete(entity);
        }

     

        private void RecursiveAreas(AreaGroup area, ref HashSet<AreaGroup> hashset)
        {
            hashset.Add(area);
            foreach (var item in area.ChildNodes)
            {
                RecursiveAreas(item, ref hashset);
            }
        }  
        #region IRecursionable<Menu> Members

        public IEnumerable<AreaGroup> Build()
        {
            IList<AreaGroup> list = new List<AreaGroup>();
            int rowIndex = 1;
            _RecursionService.Recursion(GetAll(), ref list, ref rowIndex, null);
            return list;
        }

        public IList<System.Web.Mvc.SelectListItem> BuildSelectList(object selectedValue = null, bool includeRoot = false)
        {
            IList<SelectListItem> list = new List<SelectListItem>();

            foreach (var item in Build())
            {
                SelectListItem sitem = new SelectListItem();
                sitem.Value = item.Id.ToString();

                string line = "├";
                for (int i = 0; i < item.Depth; i++)
                {
                    line += "—";
                }
                sitem.Text = string.Concat(line, item.Name);
                list.Add(sitem);
            }
            if (includeRoot)
            {
                list.Insert(0, new SelectListItem() { Text = "====", Value = "" });
            }
            return list;
        }

        #endregion
    }
}